package cn.myfirefly.utils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

public final class NetworkUtil {
	/**
	 */

	/**
	 * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public final static String getIpAddress(HttpServletRequest request) {
		// 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址

//		String ip = request.getHeader("X-Forwarded-For");
//
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			if (ip == null || ip.length() == 0
//					|| "unknown".equalsIgnoreCase(ip)) {
//				ip = request.getHeader("Proxy-Client-IP");
//			}
//			if (ip == null || ip.length() == 0
//					|| "unknown".equalsIgnoreCase(ip)) {
//				ip = request.getHeader("WL-Proxy-Client-IP");
//			}
//			if (ip == null || ip.length() == 0
//					|| "unknown".equalsIgnoreCase(ip)) {
//				ip = request.getHeader("HTTP_CLIENT_IP");
//			}
//			if (ip == null || ip.length() == 0
//					|| "unknown".equalsIgnoreCase(ip)) {
//				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//			}
//			if (ip == null || ip.length() == 0
//					|| "unknown".equalsIgnoreCase(ip)) {
//				ip = request.getRemoteAddr();
//			}
//		} else if (ip.length() > 15) {
//			String[] ips = ip.split(",");
//			for (int index = 0; index < ips.length; index++) {
//				String strIp = (String) ips[index];
//				if (!("unknown".equalsIgnoreCase(strIp))) {
//					ip = strIp;
//					break;
//				}
//			}
//		}
		
		String remoteAddr = request.getRemoteAddr();
		String forwarded = request.getHeader("X-Forwarded-For");
		String realIp = request.getHeader("X-Real-IP");

		String ip = null;
		if (realIp == null) {
			if (forwarded == null) {
				ip = remoteAddr;
			} else {
				ip = remoteAddr + "/" + forwarded;
			}
		} else {
			if (realIp.equals(forwarded)) {
				ip = realIp;
			} else {
				ip = realIp + "/" + forwarded.replaceAll("," + realIp, "");
			}
		}
		return ip;
	}

	/**
	 * 验证IP是否属于某个IP段
	 * ipSection IP段（以'-'分隔）
	 * ip 所验证的IP号码
	 */
	public static boolean ipExistsInRange(String ip, String ipSection) {

		ipSection = ipSection.trim();
		ip = ip.trim();
		int idx = ipSection.indexOf('-');
		String beginIP = ipSection.substring(0, idx);
		String endIP = ipSection.substring(idx + 1);
		return getIpTolong(beginIP) <= getIpTolong(ip) && getIpTolong(ip) <= getIpTolong(endIP);
	}

	public static long getIpTolong(String ip) {
		ip = ip.trim();
		String[] ips = ip.split("\\.");
		long ip1 = Integer.parseInt(ips[0]);
		long ip2 = Integer.parseInt(ips[1]);
		long ip3 = Integer.parseInt(ips[2]);
		long ip4 = Integer.parseInt(ips[3]);
		long ip2long = 1L * ip1 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256+ ip4;

		return ip2long;
	}
	
	@SuppressWarnings("rawtypes")
	public final static String convertParams2Str(HttpServletRequest request) {
		StringBuffer params = new StringBuffer();
		Map map=request.getParameterMap();
	    Set keSet=map.entrySet();
	    int count = keSet.size();
	    for(Iterator itr= keSet.iterator();itr.hasNext();){
	    	--count;
	        Map.Entry me=(Map.Entry)itr.next();
	        Object ok=me.getKey();
	        params.append(ok);
	        params.append("=");
	        Object ov=me.getValue();
	        if(ov instanceof String[]){  
	        	String[] value = (String[])ov;
	            for(int k = 0; k < value.length; k++){
	        		params.append(value[k]);
	        		if ((k + 1) != value.length) {
						params.append(",");
					}
	        	}
	        }else{  
	            params.append(ov.toString());
	        }
	        
	        if (count > 0) {
	        	params.append(", ");
			}
	    }
	    return params.toString();
	}
	
	@SuppressWarnings("rawtypes")
	public final static Map convertParams2Map(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		Map map=request.getParameterMap();
	    Set keSet=map.entrySet();
	    for(Iterator itr= keSet.iterator();itr.hasNext();){
	        Map.Entry me=(Map.Entry)itr.next();
	        Object ok=me.getKey();
	        Object ov=me.getValue();
	        if(ov instanceof String[]){  
	        	String[] value = (String[])ov;
	        	StringBuffer tempOv = new StringBuffer();
	            for(int k = 0; k < value.length; k++){
	            	tempOv.append(value[k]);
	        		if ((k + 1) != value.length) {
	        			tempOv.append(",");
					}
	        	}
	            params.put(ok.toString(), tempOv.toString());
	        }else{  
	            params.put(ok.toString(), ov==null?"":ov.toString());
	        }
	    }
	    return params;
	}
	
	public final static Map<String, Object> convertAttrs2Map(HttpServletRequest request) {
		Map<String, Object> attrs = new HashMap<String, Object>();
		@SuppressWarnings("unchecked")
		Enumeration<String> attrNames = request.getAttributeNames();
		String name = null;
		while(attrNames.hasMoreElements()){
			name = attrNames.nextElement();
			attrs.put(name, request.getAttribute(name));
		}
		return attrs;
	}
	
	public final static String getRequestURL(HttpServletRequest request) {
		String url = request.getRequestURI();
		int endIndex = url.indexOf('?');
		if (endIndex > 0) {
			url = url.substring(0, endIndex + 1);
		}
		endIndex = url.indexOf(';');
		if (endIndex > 0) {
			url = url.substring(0, endIndex + 1);
		}
		
		return url;
	}
}